﻿using CMS.Auth;
using CMS.DataAccess;
using CMS.Excep;
using CMS.Model;
using CMS.ServiceProvider;
using CMS.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net;
using System.Reflection;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace CMS.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public abstract class BaseController<T, U> : MyController 
        where T:BaseModel,new()
        where U : BaseServiceProvider<T>
    {
        protected const int DEF_PAGE_INDEX = 0;
        protected const int DEF_PAGE_SIZE = 20;
        protected U serviceProvider;
        public BaseController():base()
        {
            serviceProvider = ServiceLoader.GetService<U>();
        }
        
        [HttpPost,MyAuthorize(false)]
        public virtual ResponseData<T> List(dynamic? qryParam)
        {
            var index = DEF_PAGE_INDEX;
            var pageSize = DEF_PAGE_SIZE;
            if (qryParam?.pageIndex != null)
                int.TryParse(qryParam?.pageIndex?.ToString(), out index);
            if (qryParam?.pageSize != null)
                int.TryParse(qryParam?.pageSize?.ToString(), out pageSize);
            var cond = QueryConditionResolver.Resolver<T>(qryParam);
            int total = 0;
            var result = new ResponseData<T>(serviceProvider.List(cond, index, pageSize, out total));
            result.TotalCount = total;
            return result;
        }
        [HttpGet, MyAuthorize(false)]
        public virtual ResponseData<T> Get(string pk)
        {
            int total = 1;
            var result = new ResponseData<T>(serviceProvider.Get(pk));
            result.TotalCount = total;
            return result;
        }
        [HttpPost, MyAuthorize(true)]
        public virtual ResponseData<T> Save(T data)
        {
            serviceProvider.Save(data);
            var result = new ResponseData<T>(data);
            result.TotalCount = 1;
            return result;
        }
        [HttpPost, MyAuthorize(true)]
        public virtual ResponseData<string> Delete(dynamic data)
        {
            string pk = data?.pk?.ToString();
            if (pk == null) throw new MyArgException("传入参数为空");
            serviceProvider.Delete(pk);
            var result = new ResponseData<string>("操作成功");
            result.TotalCount = 1;
            return result;
        }
    }
}
